package com.eurasia.assignment.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import com.eurasia.assignment.controller.dto.LoginResponse;
import com.eurasia.assignment.domain.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.eurasia.assignment.domain.Role;
import com.eurasia.assignment.security.JwtTokenUtil;
import com.eurasia.assignment.service.UserService;

@RestController
@RequestMapping("/auth")
public class AuthController {

    private final JwtTokenUtil jwtTokenUtil;
    private final UserService userService;

    public AuthController(JwtTokenUtil jwtTokenUtil, UserService userService) {
        this.jwtTokenUtil = jwtTokenUtil;
        this.userService = userService;
    }

    @PostMapping("/login")
    public ResponseEntity<LoginResponse> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");
        String role = loginRequest.get("role");

        User user = userService.login(username, password, role);

        String token = jwtTokenUtil.generateToken(user);

        LoginResponse response = LoginResponse.builder()
                .userId(user.getId())
                .username(user.getUsername())
                .token(token)
                .role(user.getRole())
                .build();

        return ResponseEntity.ok(response);
    }
}